package ee.db;

import ee.model.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Calendar;

/**
 * User: JAAN
 * Date: 9.05.12
 */
@Service
public class UserService {
  @Autowired
  private JdbcTemplate jdbc;
  Logger logger = LoggerFactory.getLogger(UserService.class);

  public User getUser(String username) {
    return null;
  }

  public void saveUser(User user) {
    createNewUser(user);
    createProject(user.getUsername(), "CASUAL");
  }

  private void createNewUser(User user) {
    String sql = "INSERT INTO USERS (firstname, lastname, username, email, password) VALUES " +
      "('" + user.getFirstname() + "'," +
      "'" + user.getLastname() + "'," +
      "'" + user.getUsername() + "'," +
      "'" + user.getEmail() + "'," +
      "'" + user.getPassword() + "');";
    jdbc.execute(sql);
  }

  public void createProject(String userName, String projectName) {
    int userId = getUserId(userName);
    Calendar calendar = Calendar.getInstance();
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yy");
    String date = dateFormat.format(calendar.getTime());
    String sql = "INSERT INTO PROJECTS (userId, projectName, todo, deadline, priority, status, tags, comments) VALUES " +
      "(" + userId + "," +
      "'" + projectName + "'," +
      "'Create your first todo!'," +
      "STR_TO_DATE('" +  date + "','%d-%m-%Y')," +
      "'1', 'START', 'TAG', 'Welcome to MyTodo, this is a default todo.');";
    jdbc.execute(sql);
  }

  public int getUserId(String username) {
    return jdbc.queryForInt("SELECT id FROM USERS where username = '" + username + "'");
  }

  public boolean isEmailAvailable(String email) {
    return jdbc.queryForInt("SELECT count(*) FROM USERS where email = '" + email + "'") == 0;
  }

  public boolean isUsernameAvailable(String userName) {
    return jdbc.queryForInt("SELECT count(*) FROM USERS where username = '" + userName + "'") == 0;
  }

  public boolean isUserDataCorrect(String username, String password) {
    return jdbc.queryForInt("SELECT count(*) FROM USERS where username = '" + username + "' AND password = '" + password + "'") == 1;
  }
}
